<?php

// 第三方支付宝代付订单模型

namespace app\api\model;

use app\api\model\PaymentOrderNotify;
use app\api\model\PaymentCash;
use app\api\model\PaymentRedis;
use think\Model;
use think\facade\Cache;
use think\facade\Env;
use think\facade\Log;
use think\facade\Request;

class PaymentOrderAlipayPaid extends Model
{

    // 数据表名称,不包括表前缀
    protected $name = 'payment_order_alipay_paid';
    // 数据表主键
    protected $pk = 'order_id';
    // 时间字段取出后的默认时间格式
    protected $dateFormat = false;
    // Redis缓存驱动
    public $redis;

    protected function initialize()
    {
        parent::initialize();
        // redis连接缓存驱动
        $this->redis = Cache::store('redis');
        // 文件连接缓存驱动
        // $this->redis =Cache::store('file');
    }

    /**
     * 第三方代付通知相关操作
     * @access public
     * @param  string  $order_id         平台订单号
     * @param  string  $notify_param     通知参数
     * @param  string  $cash             金额
     * @param  string  $status           状态
     * @param  string  $other_order_id   第三方订单号
     * @param  string  $payment_company  第三方总代付公司
     * @param  boolean $verify_rule      验证订单规则
     * @param  boolean $verify_sign      验证sign
     * @param  boolean $all_order_verify 内部绿色通道
     * @return mixed
     */
    public function notifyAbout($order_id = 0, $notify_param = '', $cash = 0, $status = 0, $other_order_id = 0, $payment_company = '', $verify_rule = true, $verify_sign = false, $all_order_verify = true)
    {

        // 查找订单
        $order_arr = self::where(['order_id' => $order_id])->find();
        if ($order_arr) {

            // 内部绿色通道，是否关闭验证（比如模拟第三方通知）
            if ($all_order_verify) {

                $company_config = $this->redis->get($order_arr['child_company']);
                if (!$company_config) {
                    abort(404, "平台订单号是（{$order_arr['order_id']}）：验证第三方代付订单状态，（{$order_arr['child_company']}）代付公司配置错误");
                }

                // 代付公司订单验证开启
                if ($company_config['value']['company_order_verify']) {

                    // $verify_rule为true验证第三方订单，为false验证平台订单号
                    $verify_order_id = $verify_rule ? $other_order_id : $order_id;

                    // 实例化第三方订单模型                
                    $company = $order_arr['company'] . 'PaidQuery';

                    $verify = $this->$company($verify_order_id, $company_config['value'], $order_arr, true, false);
                    if (!$verify) {
                        abort(404, "平台订单号是（{$order_arr['order_id']}）：代付接口查询异常：（第三方系统异常）第三方代付子公司（{$order_arr['child_company']}），第三方订单号是（{$other_order_id}）");
                    }
                    if ($verify != $status) {
                        abort(404, "平台订单号是（{$order_arr['order_id']}）：代付接口查询异常：查询状态（{$verify}）和通知状态（{$status}）不一样，第三方代付子公司（{$order_arr['child_company']}），第三方订单号是（{$other_order_id}）");
                    }
                }

                // 访问请求ip地址
                $request_ip = Request::instance()->ip();
                if ($company_config['value']['notify_ip']) {
                    if (!in_array($request_ip, $company_config['value']['notify_ip'])) {
                        abort(404, "平台订单号是（{$order_arr['order_id']}）：上游服务端通知IP（{$request_ip}）不在白名单中");
                    }
                }

                // 是否验证sign
                if ($verify_sign) {
                    $company = $order_arr['company'] . 'Sign';
                    $sign = $this->$company($order_id, $company_config['value']);
                    if (!$sign) {
                        abort(404, "平台订单号是（{$order_arr['order_id']}）：验证sign失败");
                    }
                }

                // 是否接收通知
                if ($company_config['value']['notify_open'] != 1) {
                    abort(404, "平台订单号是（{$order_arr['order_id']}）：代付通知关闭");
                }
            }

            // 订单状态：1:处理中 2:成功 3:失败 4:异常
            switch ($order_arr['status']) {
                    // 处理中
                case '1':
                    // 默认代付订单要在30天内完成
                    if (time() > $order_arr['create_time'] + 86400 * 30) {
                        $remark = "第三方{$order_arr['company']}代付，默认代付订单要在30天内完成";
                    }
                    // 验证公司
                    if ($order_arr['company'] != $payment_company) {
                        $remark = "涉嫌修改第三方代付公司{$order_arr['company']}名称：{$payment_company}";
                    }
                    // 验证金额
                    if ($order_arr['cash'] != intval(strval($cash * 100))) {
                        $remark = "涉嫌修改第三方代付公司{$order_arr['company']}的代付金额：{$cash}";
                    }
                    if (isset($remark)) {
                        self::where(['order_id' => $order_id, 'status' => 1])
                            ->update(['remark' => $remark, 'status' => 4, 'other_order_id' => $other_order_id, 'update_time' => time()]);
                        payment_error_log(640000, $notify_param);
                        abort(404, $remark);
                    }

                    // 第三方可能会在一秒中多次通知相同订单，用redis处理。
                    $order_notify_key = 'order_notify_' . $order_arr['order_id'];
                    $order_notify = $this->redis->has($order_notify_key);
                    if ($order_notify) {
                        $this->redis->inc($order_notify_key, 1);
                        //payment_error_log(640001, $order_arr);
                        abort(404, "{$order_arr['company']}代付，订单通知有误1，原因可能是代付公司在一秒中多次通知相同订单");
                    } else {
                        $this->redis->set($order_notify_key, 1, 5);
                    }
                    $order_notify_value = $this->redis->get($order_notify_key);
                    if (!$order_notify_value || $order_notify_value > 1) {
                        payment_error_log(640002, $order_arr);
                        abort(404, "{$order_arr['company']}代付，订单通知有误2，原因可能是代付公司在一秒中多次通知相同订单");
                    }

                    $payment_order_data = [
                        'status' => $status,
                        'notify_param' => json_encode($notify_param, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                        'other_order_id' => $other_order_id,
                        'update_time' => time(),
                    ];
                    // 更新代付订单表状态
                    try {
                        $update_data = self::where(['order_id' => $order_id, 'status' => 1])->update($payment_order_data);
                    } catch (\Exception $e) {
                        payment_error_log(640003, $order_arr, $e->getMessage());
                        abort(404, "更新代付订单表状态失败1,{$order_arr['company']}代付");
                    }
                    if ($update_data) {
                        return $this->paySuccess($order_arr, $other_order_id, $status);
                    } else {
                        payment_error_log(640004, $order_arr);
                        abort(404, "更新代付订单表状态失败2,{$order_arr['company']}支付");
                    }

                    // 订单已经代付完成（成功）
                case '2':
                    //payment_error_log(640005, $order_arr, "可能是第三方用了(多台服务器通知)，也有可能是第一次代付公司（{$order_arr['company']}）通知出现异常，状态已经修改，但是没有返回success", false);
                    return 'success';
                    // 订单已经代付完成（失败）
                case '3':
                    //payment_error_log(640005, $order_arr, "可能是第三方用了(多台服务器通知)，也有可能是第一次代付公司（{$order_arr['company']}）通知出现异常，状态已经修改，但是没有返回success", false);
                    return 'success';
                default:
                    // 状态错误
                    abort(404, "订单代付状态错误,现在状态是（{$order_arr['status']}）");
            }
        } else {
            // 订单号不存在
        }
        abort(404, '可能是别人在模拟第三方通知，或者程序出现异常');
    }

    /**
     * 成功相关操作
     * @access public
     * @param  array  $order_arr       订单数组
     * @param  string $other_order_id  第三方订单号
     * @param  string $order_status    状态
     * @return mixed
     */
    public function paySuccess($order_arr = [], $other_order_id = 0, $order_status = 0)
    {

        // 第三方可能会在一秒中多次通知相同订单，用redis处理。
        $order_notify_key = 'merchant_order_notify_' . $order_arr['order_id'];
        $order_notify = $this->redis->has($order_notify_key);
        if ($order_notify) {
            payment_error_log(640006, $order_arr);
            abort(404, "{$order_arr['company']}代付，订单通知有误2，原因可能是代付公司在一秒中多次通知相同订单");
        } else {
            $this->redis->set($order_notify_key, 1, 5);
        }

        // 失败：代付金额退回
        if ($order_status == 3) {
            // 代付绿色通道
            if ($order_arr['paid_green_channel_status'] == 0) {
                try {
                    PaymentCash::where(['merchant_id' => $order_arr['merchant_id']])
                        ->inc('paid_cash', $order_arr['deduct_cash'])
                        ->dec('paid_sum_cash', $order_arr['deduct_cash'])
                        ->dec('paid_count', 1)
                        ->update(['update_time' => time()]);
                } catch (\Exception $e) {
                    payment_error_log(640007, $order_arr, $e->getMessage());
                }
            }
        }
        // 成功：处理商户等配置
        if ($order_status == 2) {

            // 指定代付公司不执行
            if (!in_array($order_arr['company'], ['zfb'])) {

                $paid_cash = $order_arr['cash'];
                $expire = strtotime(date('Y-m-d', strtotime('+1 day'))) - time();

                // 更新商户号今天已经代付的金额总数
                $merchant_day_alipay_paid_cash_sum = $order_arr['merchant_id'] . '_day_alipay_paid_cash_sum';
                $now_merchant_day_alipay_paid_cash_sum = $this->redis->has($merchant_day_alipay_paid_cash_sum);
                if ($now_merchant_day_alipay_paid_cash_sum) {
                    $this->redis->inc($merchant_day_alipay_paid_cash_sum, $paid_cash);
                } else {
                    $this->redis->set($merchant_day_alipay_paid_cash_sum, $paid_cash, $expire);
                }

                // 更新代付公司中的子商户号今天已经代付的金额总数
                $children_day_paid_cash_sum = $order_arr['child_company'] . '_day_paid_cash_sum';
                $now_children_day_paid_cash_sum = $this->redis->has($children_day_paid_cash_sum);
                if ($now_children_day_paid_cash_sum) {
                    $this->redis->inc($children_day_paid_cash_sum, $paid_cash);
                } else {
                    $this->redis->set($children_day_paid_cash_sum, $paid_cash, $expire);
                }

                // 通道每天最多代付成功次数
                $children_company_success_count = $order_arr['child_company'] . '_success_count';
                $now_children_company_success_count = $this->redis->has($children_company_success_count);
                if ($now_children_company_success_count) {
                    $this->redis->inc($children_company_success_count, 1);
                } else {
                    $this->redis->set($children_company_success_count, 1, $expire);
                }

                // 代付公司中的子公司商户号配置
                $children_company_config = $this->redis->get($order_arr['child_company']);
                if ($children_company_config['value']['user_success_count'] != '0') {
                    // 通道每天最多代付用户成功次数（支付宝）
                    $children_company_user_success_count = $order_arr['child_company'] . '_user_' . $order_arr['account'];
                    $now_children_company_user_success_count = $this->redis->has($children_company_user_success_count);
                    if ($now_children_company_user_success_count) {
                        $this->redis->inc($children_company_user_success_count, 1);
                    } else {
                        $this->redis->set($children_company_user_success_count, 1, $expire);
                    }
                }
            }
        }

        // 把代付信息通知给商户
        $merchant_create_param = json_decode($order_arr['create_param'], true);
        // 商户开启通知
        if ($merchant_create_param['notify_open'] == 1) {
            $notify_url = $merchant_create_param['notify_url'];
            $notify_data['code'] = 10000;                                           // 成功状态码
            $notify_data['merchant_id'] = $order_arr['merchant_id'];                // 商户号
            $notify_data['merchant_order_id'] = $order_arr['merchant_order_id'];    // 商户订单号
            $notify_data['order_id'] = $order_arr['order_id'];                      // 代付订单号
            $notify_data['app_id'] = $order_arr['app_id'];                          // 应用id
            $notify_data['cash'] = $order_arr['cash'] / 100;                        // 代付现金    
            $notify_data['deduct_cash'] = $order_arr['deduct_cash'] / 100;          // 扣除金额    
            $notify_data['mode'] = $order_arr['mode'];                              // 代付方法：0自动，1手动
            $notify_data['trade_type'] = $order_arr['trade_type'];                  // 交易类型：比如充值、代付                                  
            $notify_data['body'] = $order_arr['body'];                              // 代付说明
            $notify_data['time'] = time();                                          // 更新时间
            $notify_data['extra'] = $merchant_create_param['extra'];                // 商户自定义备注
            // 订单状态：1:处理中 2:成功 3:失败 4:异常
            $notify_data['status'] = $order_status;
            $notify_data['sign'] = md5('merchant_id=' . $notify_data['merchant_id'] . '&merchant_order_id=' . $notify_data['merchant_order_id'] . '&order_id=' . $notify_data['order_id'] . '&cash=' . $notify_data['cash'] . '&status=' . $notify_data['status'] . '&time=' . $notify_data['time'] . '&key=' . $merchant_create_param['key']);

            $resdata = go_curl($notify_url, $notify_data, 'get', 12);
            if (stripos($resdata, 'success') === false) {
                // 通知失败,准备多次通知
                $url_param = http_build_query($notify_data);
                $url = strpos($notify_url, '?') !== false ? $notify_url . '&' . $url_param : $notify_url . '?' . $url_param;

                $notify_array = [
                    'order_id' => $order_arr['order_id'],
                    'merchant_id' => $order_arr['merchant_id'],
                    'merchant_order_id' => $order_arr['merchant_order_id'],
                    'other_order_id' => $other_order_id,
                    'app_id' => $order_arr['app_id'],
                    'cash' => $order_arr['cash'],
                    'type' => 0,
                    'trade_type' => $order_arr['trade_type'],
                    'status' => 0,
                    'manual' => 0,
                    'count' => 0,
                    'create_time' => $order_arr['create_time'],
                    'update_time' => time(),
                    'url' => $url,
                    'remark' => substr($resdata, 0, 60000),
                ];
                // 插入多次通知数据库
                try {
                    PaymentOrderNotify::create($notify_array);
                } catch (\Exception $e) {
                    payment_error_log(640008, $notify_array, $e->getMessage());
                }

                Log::record("代付通知商户号{$order_arr['merchant_id']}失败记录：" . $order_arr['order_id'] . '——' . '0', 'log');
                Log::record('代付通知URL参数：' . $url, 'log');
                Log::record('代付通知返回内容：' . $resdata, 'log');
            }
        }

        // 处理完数据，给第三方代付返回接收成功
        return 'success';
    }

    /**
     * 支付宝代付
     * @access public
     * @param  array  $parameters   创建订单参数
     * @param  array  $pay_config   代付配置
     * @return array
     */
    public function zfbPaid($parameters = [], $pay_config = [])
    {

        $this->dayStatistics($parameters, $pay_config, 1);

        if ($pay_config['other_four'] == 1) {
            include_once Env::get('extend_path') . 'alipaySdk/aop/AopClient.php';
            include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayFundTransToaccountTransferRequest.php';

            $aop = new \AopClient();
            // 正式环境
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            // 支付宝分配给开发者的应用ID
            $aop->appId = $pay_config['app_id'];
            // 请填写开发者私钥去头去尾去回车，一行字符串
            $aop->rsaPrivateKey = $pay_config['key'];
            // 请填写支付宝公钥，一行字符串
            $aop->alipayrsaPublicKey = $pay_config['other_public_key'];
            // 调用的接口版本，固定为：1.0
            $aop->apiVersion = '1.0';
            // 商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $aop->signType = 'RSA2';
            // 请求使用的编码格式，如utf-8,gbk,gb2312等
            $aop->postCharset = 'utf-8';
            // 仅支持JSON
            $aop->format = 'json';
            $request = new \AlipayFundTransToaccountTransferRequest();
            // 商户转账唯一订单号。
            //$out_biz_no = date('YmdHis') . rand(100000, 999999);
            /*
              收款方账户类型。可取值：
              1、ALIPAY_USERID：支付宝账号对应的支付宝唯一用户号。以2088开头的16位纯数字组成。
              2、ALIPAY_LOGONID：支付宝登录号，支持邮箱和手机号格式。
             */
            //$payee_type = 'ALIPAY_LOGONID';
            /*
              收款方账户。与payee_type配合使用。付款方和收款方不能是同一个账户。
             */
            //$payee_account = 13888888888;
            /*
              转账金额，单位：元。
              只支持2位小数，小数点前最大支持13位，金额必须大于等于0.1元。
              最大转账金额以实际签约的限额为准。
             */
            //$amount = 0.01;
            /*
              可选
              付款方姓名（最长支持100个英文/50个汉字）。显示在收款方的账单详情页。如果该字段不传，则默认显示付款方的支付宝认证姓名或单位名称。
             */
            //$payer_show_name = '付款方姓名';
            /*
              可选
              收款方真实姓名（最长支持100个英文/50个汉字）。
              如果本参数不为空，则会校验该账户在支付宝登记的实名是否与收款方真实姓名一致。
             */
            //$payee_real_name = '收款方真实姓名';
            /*
              可选
              转账备注（支持200个英文/100个汉字）。
              当付款方为企业账户，且转账金额达到（大于等于）50000元，remark不能为空。收款方可见，会展示在收款用户的收支详情中。
             */
            //$remark = '转账';

            $request->setBizContent("{" .
                "\"out_biz_no\":\"{$parameters['order_id']}\"," .
                "\"payee_type\":\"ALIPAY_LOGONID\"," .
                "\"payee_account\":\"{$parameters['account']}\"," .
                "\"amount\":\"{$parameters['cash']}\"," .
                "\"payer_show_name\":\"{$pay_config['other_five']}\"," .
                "\"payee_real_name\":\"{$parameters['name']}\"," .
                "\"remark\":\"转账\"" .
                "}");
            $result = $aop->execute($request);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;

            if (!empty($resultCode) && $resultCode == 10000) {
                return ['code' => 200, 'other_order_id' => $result->alipay_fund_trans_toaccount_transfer_response->order_id, 'msg' => '成功', 'return_param' => json_encode($result)];
            } else {
                $this->dayStatistics($parameters, $pay_config, 0);
                return ['code' => 300, 'other_order_id' => 0, 'msg' => $result->alipay_fund_trans_toaccount_transfer_response->sub_msg, 'return_param' => json_encode($result)];
            }
        }



        // 支付宝证书版
        include_once Env::get('extend_path') . 'alipaySdk/aop/AopCertClient.php';
        include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayFundTransUniTransferRequest.php';

        $aop = new \AopCertClient();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = $pay_config['app_id'];
        $aop->rsaPrivateKey = $pay_config['key'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';

        /*
          // 应用公钥证书
          $appCertPath = Env::get('root_path') . 'cert' . DIRECTORY_SEPARATOR . 'alipay' . DIRECTORY_SEPARATOR . $pay_config['other_one'] . '_app_cert.crt';
          // 支付宝公钥证书
          $alipayCertPath = Env::get('root_path') . 'cert' . DIRECTORY_SEPARATOR . 'alipay' . DIRECTORY_SEPARATOR . $pay_config['other_two'] . '_alipay_cert.crt';
          // 支付宝根证书
          $rootCertPath = Env::get('root_path') . 'cert' . DIRECTORY_SEPARATOR . 'alipay' . DIRECTORY_SEPARATOR . $pay_config['other_three'] . '_root_cert.crt';

          $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
          $aop->appCertSN = $aop->getCertSN($appCertPath);
          $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
         */

        $pkey = openssl_pkey_get_public($pay_config['other_two']);
        $keyData = openssl_pkey_get_details($pkey);
        $public_key = str_replace('-----BEGIN PUBLIC KEY-----', '', $keyData['key']);
        $aop->alipayrsaPublicKey = trim(str_replace('-----END PUBLIC KEY-----', '', $public_key));

        $ssl = openssl_x509_parse($pay_config['other_one']);
        $aop->appCertSN = md5(array2string(array_reverse($ssl['issuer'])) . $ssl['serialNumber']);

        $aop->alipayRootCertContent = $pay_config['other_three'];
        $array = explode("-----END CERTIFICATE-----", $pay_config['other_three']);
        $SN = null;
        for ($i = 0; $i < count($array) - 1; $i++) {
            $ssl[$i] = openssl_x509_parse($array[$i] . "-----END CERTIFICATE-----");
            if (strpos($ssl[$i]['serialNumber'], '0x') === 0) {
                $ssl[$i]['serialNumber'] = $this->hex2dec($ssl[$i]['serialNumber']);
            }
            if ($ssl[$i]['signatureTypeLN'] == "sha1WithRSAEncryption" || $ssl[$i]['signatureTypeLN'] == "sha256WithRSAEncryption") {
                if ($SN == null) {
                    $SN = md5(array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']);
                } else {

                    $SN = $SN . "_" . md5(array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']);
                }
            }
        }
        $aop->alipayRootCertSN = $SN;

        $request = new \AlipayFundTransUniTransferRequest();

        $biz_content = [
            'out_biz_no' => $parameters['order_id'], // 商户端的唯一订单号
            'trans_amount' => $parameters['cash'], // 订单总金额
            'product_code' => 'TRANS_ACCOUNT_NO_PWD', // 业务产品码，单笔无密转账到支付宝账户固定为:TRANS_ACCOUNT_NO_PWD；单笔无密转账到银行卡固定为:TRANS_BANKCARD_NO_PWD;收发现金红包固定为:STD_RED_PACKET；
            'biz_scene' => 'DIRECT_TRANSFER', // 描述特定的业务场景，可传的参数如下：DIRECT_TRANSFER：单笔无密转账到支付宝/银行卡, B2C现金红包;PERSONAL_COLLECTION：C2C现金红包-领红包
            'order_title' => '转账' . $parameters['order_id'], // 转账业务的标题
            'payee_info' => [
                'identity' => $parameters['account'], // 参与方的唯一标识
                'identity_type' => 'ALIPAY_LOGON_ID', // 参与方的标识类型，目前支持如下类型： 1、ALIPAY_USER_ID 支付宝的会员ID 2、ALIPAY_LOGON_ID：支付宝登录号，支持邮箱和手机号格式
                'name' => $parameters['name'], // 参与方真实姓名
            ], // 收款方信息
            'business_params' => [
                'payer_show_name' => $pay_config['other_five'], // 商户企业名称 
            ], // 转账业务请求的扩展参数
        ];
        $biz_content_json = json_encode($biz_content);

        $request->setBizContent($biz_content_json);
        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;

        if (!empty($resultCode) && $resultCode == 10000) {
            return ['code' => 200, 'other_order_id' => $result->$responseNode->order_id, 'msg' => '成功', 'return_param' => json_encode($result)];
        } else {
            $this->dayStatistics($parameters, $pay_config, 0);

            // 余额不足，自动设置关闭
            if ($result->$responseNode->sub_code == 'BALANCE_IS_NOT_ENOUGH') {
                // 余额不足，建议尽快充值。后续可登录电脑端支付宝，自主设置余额预警提醒功能。
                $redis_find = PaymentRedis::where(['name' => $pay_config['name']])->find();
                if ($redis_find) {
                    PaymentRedis::where(['name' => $pay_config['name']])->update(['status' => 0, 'update_time' => time()]);

                    $redis_config = PaymentRedis::where(['name' => $pay_config['name']])->order(['name' => 'asc'])->column('*', 'name');
                    foreach ($redis_config as $k => &$v) {
                        //json转换成数组
                        if (!is_null(json_decode($v['value']))) {
                            $v['value'] = json_decode($v['value'], true);
                        }
                        $this->redis->set($k, $v);
                    }
                }
            }

            return ['code' => 300, 'other_order_id' => 0, 'msg' => $result->$responseNode->sub_msg, 'return_param' => json_encode($result)];
        }
    }

    /**
     * 支付宝代付，验证订单号，是不是已经代付成功
     * @access public
     * @param  string   $order_id     本地订单号（第三方订单号）
     * @param  array    $pay_config   代付配置
     * @param  array    $other_param  其他参数
     * @param  boolean  $rule         返回规则
     * @param  boolean  $query_type   查询类型
     * @return array
     */
    public function zfbPaidQuery($order_id = 0, $pay_config = [], $other_param = [], $rule = false, $query_type = false)
    {

        if ($pay_config['other_four'] == 1) {
            if ($query_type) {
                $other_return_param_array = json_decode($other_param['return_param'], true);
                if (isset($other_return_param_array['alipay_fund_trans_toaccount_transfer_response']['code']) && $other_return_param_array['alipay_fund_trans_toaccount_transfer_response']['code'] == '10000') {
                    $other_return_param_to_json = [];
                    $other_return_param_to_json['alipay_fund_trans_order_query_response']['msg'] = '自定义成功';
                    $other_return_param_to_json['alipay_fund_trans_order_query_response']['status'] = 'SUCCESS';
                    return ['code' => 200, 'return_param' => json_encode($other_return_param_to_json), 'data' => ''];
                }
            }

            include_once Env::get('extend_path') . 'alipaySdk/aop/AopClient.php';
            include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayFundTransOrderQueryRequest.php';

            $aop = new \AopClient();
            // 正式环境
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            // 支付宝分配给开发者的应用ID
            $aop->appId = $pay_config['app_id'];
            // 请填写开发者私钥去头去尾去回车，一行字符串
            $aop->rsaPrivateKey = $pay_config['key'];
            // 请填写支付宝公钥，一行字符串
            $aop->alipayrsaPublicKey = $pay_config['other_public_key'];
            // 调用的接口版本，固定为：1.0
            $aop->apiVersion = '1.0';
            // 商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $aop->signType = 'RSA2';
            // 请求使用的编码格式，如utf-8,gbk,gb2312等
            $aop->postCharset = 'utf-8';
            // 仅支持JSON
            $aop->format = 'json';
            $request = new \AlipayFundTransOrderQueryRequest();

            $request->setBizContent("{" .
                "\"out_biz_no\":\"{$order_id}\"," .
                "\"order_id\":\"\"" .
                "  }");
            $result = $aop->execute($request);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;

            if (!empty($resultCode) && $resultCode == 10000) {
                return ['code' => 200, 'return_param' => substr(json_encode($result), 0, 60000), 'data' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
            } else {
                return ['code' => 300, 'return_param' => substr(json_encode($result), 0, 60000), 'data' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
            }
        }



        // 支付宝证书版
        if ($query_type) {
            $other_return_param_array = json_decode($other_param['return_param'], true);
            if (isset($other_return_param_array['alipay_fund_trans_uni_transfer_response']['code']) && $other_return_param_array['alipay_fund_trans_uni_transfer_response']['code'] == '10000') {
                $other_return_param_to_json = [];
                $other_return_param_to_json['alipay_fund_trans_common_query_response']['msg'] = '自定义成功';
                $other_return_param_to_json['alipay_fund_trans_common_query_response']['status'] = 'SUCCESS';
                return ['code' => 200, 'return_param' => json_encode($other_return_param_to_json), 'data' => ''];
            }
        }

        include_once Env::get('extend_path') . 'alipaySdk/aop/AopCertClient.php';
        include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayFundTransCommonQueryRequest.php';

        $aop = new \AopCertClient();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = $pay_config['app_id'];
        $aop->rsaPrivateKey = $pay_config['key'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';

        /*
          // 应用公钥证书
          $appCertPath = Env::get('root_path') . 'cert' . DIRECTORY_SEPARATOR . 'alipay' . DIRECTORY_SEPARATOR . $pay_config['other_one'] . '_app_cert.crt';
          // 支付宝公钥证书
          $alipayCertPath = Env::get('root_path') . 'cert' . DIRECTORY_SEPARATOR . 'alipay' . DIRECTORY_SEPARATOR . $pay_config['other_two'] . '_alipay_cert.crt';
          // 支付宝根证书
          $rootCertPath = Env::get('root_path') . 'cert' . DIRECTORY_SEPARATOR . 'alipay' . DIRECTORY_SEPARATOR . $pay_config['other_three'] . '_root_cert.crt';

          $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
          $aop->appCertSN = $aop->getCertSN($appCertPath);
          $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
         */

        $pkey = openssl_pkey_get_public($pay_config['other_two']);
        $keyData = openssl_pkey_get_details($pkey);
        $public_key = str_replace('-----BEGIN PUBLIC KEY-----', '', $keyData['key']);
        $aop->alipayrsaPublicKey = trim(str_replace('-----END PUBLIC KEY-----', '', $public_key));

        $ssl = openssl_x509_parse($pay_config['other_one']);
        $aop->appCertSN = md5(array2string(array_reverse($ssl['issuer'])) . $ssl['serialNumber']);

        $aop->alipayRootCertContent = $pay_config['other_three'];
        $array = explode("-----END CERTIFICATE-----", $pay_config['other_three']);
        $SN = null;
        for ($i = 0; $i < count($array) - 1; $i++) {
            $ssl[$i] = openssl_x509_parse($array[$i] . "-----END CERTIFICATE-----");
            if (strpos($ssl[$i]['serialNumber'], '0x') === 0) {
                $ssl[$i]['serialNumber'] = $this->hex2dec($ssl[$i]['serialNumber']);
            }
            if ($ssl[$i]['signatureTypeLN'] == "sha1WithRSAEncryption" || $ssl[$i]['signatureTypeLN'] == "sha256WithRSAEncryption") {
                if ($SN == null) {
                    $SN = md5(array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']);
                } else {

                    $SN = $SN . "_" . md5(array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']);
                }
            }
        }
        $aop->alipayRootCertSN = $SN;

        $request = new \AlipayFundTransCommonQueryRequest();

        $biz_content = [
            'product_code' => 'TRANS_ACCOUNT_NO_PWD', // 销售产品码，商家和支付宝签约的产品码，如果传递了out_biz_no则该字段为必传。可传值如下：STD_RED_PACKET：现金红包 TRANS_ACCOUNT_NO_PWD：单笔无密转账到支付宝账户 TRANS_BANKCARD_NO_PWD：单笔无密转账到银行卡
            'biz_scene' => 'DIRECT_TRANSFER', // 描述特定的业务场景，如果传递了out_biz_no则该字段为必传。可取的业务场景如下： PERSONAL_PAY：C2C现金红包-发红包；PERSONAL_COLLECTION：C2C现金红包-领红包； REFUND：C2C现金红包-红包退回； DIRECT_TRANSFER：B2C现金红包、单笔无密转账
            'out_biz_no' => $order_id, // 商户转账唯一订单号
        ];
        $biz_content_json = json_encode($biz_content);

        $request->setBizContent($biz_content_json);
        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;

        if (!empty($resultCode) && $resultCode == 10000) {
            return ['code' => 200, 'return_param' => substr(json_encode($result), 0, 60000), 'data' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
        } else {
            return ['code' => 300, 'return_param' => substr(json_encode($result), 0, 60000), 'data' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
        }
    }

    /**
     * 支付宝代付，查询帐号余额
     * @access public
     * @param  array   $pay_config  代付配置
     * @return array
     */
    public function zfbPaidQueryCash($pay_config = [])
    {

        if ($pay_config['other_four'] == 1) {
            include_once Env::get('extend_path') . 'alipaySdk/aop/AopClient.php';
            include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayFundAccountQueryRequest.php';

            $aop = new \AopClient();
            // 正式环境
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            // 支付宝分配给开发者的应用ID
            $aop->appId = $pay_config['app_id'];
            // 请填写开发者私钥去头去尾去回车，一行字符串
            $aop->rsaPrivateKey = $pay_config['key'];
            // 请填写支付宝公钥，一行字符串
            $aop->alipayrsaPublicKey = $pay_config['other_public_key'];
            // 调用的接口版本，固定为：1.0
            $aop->apiVersion = '1.0';
            // 商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $aop->signType = 'RSA2';
            // 请求使用的编码格式，如utf-8,gbk,gb2312等
            $aop->postCharset = 'utf-8';
            // 仅支持JSON
            $aop->format = 'json';
            $request = new \AlipayFundAccountQueryRequest();
            $request->setBizContent("{" .
                "\"alipay_user_id\":\"{$pay_config['merchant_id']}\"," .
                "\"merchant_user_id\":\"\"," .
                "\"account_product_code\":\"\"," .
                "\"account_type\":\"ACCTRANS_ACCOUNT\"," .
                "\"account_scene_code\":\"\"," .
                "\"ext_info\":\"\"" .
                "  }");
            $result = $aop->execute($request);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;

            if (!empty($resultCode) && $resultCode == 10000) {
                return ['code' => 200, 'return_param' => substr(json_encode($result), 0, 60000), 'cash' => $result->$responseNode->available_amount, 'data' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
            } else {
                return ['code' => 300, 'return_param' => substr(json_encode($result), 0, 60000), 'cash' => 0, 'data' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
            }
        }



        // 支付宝证书版
        include_once Env::get('extend_path') . 'alipaySdk/aop/AopCertClient.php';
        include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayFundAccountQueryRequest.php';

        $aop = new \AopCertClient();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = $pay_config['app_id'];
        $aop->rsaPrivateKey = $pay_config['key'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';

        /*
          // 应用公钥证书
          $appCertPath = Env::get('root_path') . 'cert' . DIRECTORY_SEPARATOR . 'alipay' . DIRECTORY_SEPARATOR . $pay_config['other_one'] . '_app_cert.crt';
          // 支付宝公钥证书
          $alipayCertPath = Env::get('root_path') . 'cert' . DIRECTORY_SEPARATOR . 'alipay' . DIRECTORY_SEPARATOR . $pay_config['other_two'] . '_alipay_cert.crt';
          // 支付宝根证书
          $rootCertPath = Env::get('root_path') . 'cert' . DIRECTORY_SEPARATOR . 'alipay' . DIRECTORY_SEPARATOR . $pay_config['other_three'] . '_root_cert.crt';

          $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
          $aop->appCertSN = $aop->getCertSN($appCertPath);
          $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
         */

        $pkey = openssl_pkey_get_public($pay_config['other_two']);
        $keyData = openssl_pkey_get_details($pkey);
        $public_key = str_replace('-----BEGIN PUBLIC KEY-----', '', $keyData['key']);
        $aop->alipayrsaPublicKey = trim(str_replace('-----END PUBLIC KEY-----', '', $public_key));

        $ssl = openssl_x509_parse($pay_config['other_one']);
        $aop->appCertSN = md5(array2string(array_reverse($ssl['issuer'])) . $ssl['serialNumber']);

        $aop->alipayRootCertContent = $pay_config['other_three'];
        $array = explode("-----END CERTIFICATE-----", $pay_config['other_three']);
        $SN = null;
        for ($i = 0; $i < count($array) - 1; $i++) {
            $ssl[$i] = openssl_x509_parse($array[$i] . "-----END CERTIFICATE-----");
            if (strpos($ssl[$i]['serialNumber'], '0x') === 0) {
                $ssl[$i]['serialNumber'] = $this->hex2dec($ssl[$i]['serialNumber']);
            }
            if ($ssl[$i]['signatureTypeLN'] == "sha1WithRSAEncryption" || $ssl[$i]['signatureTypeLN'] == "sha256WithRSAEncryption") {
                if ($SN == null) {
                    $SN = md5(array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']);
                } else {

                    $SN = $SN . "_" . md5(array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']);
                }
            }
        }
        $aop->alipayRootCertSN = $SN;

        $request = new \AlipayFundAccountQueryRequest();

        $biz_content = [
            'alipay_user_id' => $pay_config['merchant_id'], // 蚂蚁统一会员ID
            'merchant_user_id' => '', // 商户会员的唯一标识
            'account_product_code' => '', // 开户产品码。如果查询托管子户余额，必传且必须传入与开户时传入的值一致。
            'account_type' => 'ACCTRANS_ACCOUNT', // 查询的账号类型，如查询托管账户值为TRUSTEESHIP_ACCOUNT，查询余额账户值为ACCTRANS_ACCOUNT。查询余额账户时必填。
            'account_scene_code' => '', // 开户场景码，与开户产品码不可同时传递。
            'ext_info' => '', // JSON格式，传递业务扩展参数。
        ];
        $biz_content_json = json_encode($biz_content);

        $request->setBizContent($biz_content_json);
        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;

        if (!empty($resultCode) && $resultCode == 10000) {
            return ['code' => 200, 'return_param' => substr(json_encode($result), 0, 60000), 'cash' => $result->$responseNode->available_amount, 'data' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
        } else {
            return ['code' => 300, 'return_param' => substr(json_encode($result), 0, 60000), 'cash' => 0, 'data' => json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
        }
    }

    /**
     * 游易付支付宝代付
     * @access public
     * @param  array  $parameters   创建订单参数
     * @param  array  $pay_config   代付配置
     * @return array
     */
    public function youyifuPaid($parameters = [], $pay_config = [])
    {
        try {

            // 此通道只能接收整数
            if ($parameters['cash'] > intval($parameters['cash'])) {
                return ['code' => 300, 'other_order_id' => 100, 'msg' => '金额必须为整数', 'return_param' => ''];
            }

            $ip_card_array = ['430525199011017218', '420123198312034141', '429006198507190335', '522401199302149015', '430419197108274550', '500223199411258853', '522121199402163817', '360428198105200030'];
            shuffle($ip_card_array);
            $ip_card = $ip_card_array[0];

            $arr['service'] = 'bankcardtransfer';                          // 接口类型
            $arr['version'] = '1.0';                                       // 版本号
            $arr['charset'] = 'UTF-8';                                     // 字符集
            $arr['mch_id'] = $pay_config['merchant_id'];                   // 商户号，由平台分配
            $arr['out_trade_no'] = $parameters['order_id'];                // 商户系统内部的订单号 ,32个字符内、 可包含字母,确保在商户系统唯一
            $arr['body'] = '转账';                                         // 放款备注    $parameters['body']
            $arr['total_fee'] = $parameters['cash'];                       // 放款金额，以元为单位，不允许包含任何字、符号
            $arr['bankaccountname'] = $parameters['name'];                 // 收款人姓名
            $arr['bankaccountno'] = $parameters['account'];                // 收款人银行卡号
            $arr['notify_url'] = $pay_config['notify_url'];                // 异步通知地址
            $arr['certno'] = $ip_card;                                     // 收款人身份证号码
            /*
              if ($parameters['account_type'] == 1) {
              $arr['publicaccount'] = $parameters['account_type'];       // 0为对个人用户出款，1为对公户出款（未提供此参数表示为对个人用户出款）
              $arr['certno'] = $parameters['bank_code'];                 // 银行编号
              }
             */
            $arr['nonce_str'] = $parameters['order_id'];                   // 随机字符串，不长于 32 位

            ksort($arr);                                                   // 对数组进行排序
            $temp = '';
            foreach ($arr as $k => $v) {
                if ($v != null) {
                    $temp = $temp . $k . '=' . $v . '&';                   // 遍历数组进行字符串的拼接
                }
            }
            $temp = substr($temp, 0, strlen($temp) - 1);

            $key = $pay_config['key'];
            $str = chunk_split($key, 64, "\n");
            $private_key = "-----BEGIN RSA PRIVATE KEY-----\n$str-----END RSA PRIVATE KEY-----\n";
            //$private_key = $pay_config['key'];                           // 私钥文件名获取私钥(内容)

            $pkey_get_private = openssl_pkey_get_private($private_key);    // 获取私钥
            $signature = '';
            openssl_sign($temp, $signature, $pkey_get_private, OPENSSL_ALGO_SHA1);    // 生成一个签名

            $arr['sign'] = base64_encode($signature);

            $json = json_encode($arr);
            $request_url = $pay_config['request_url'];                     // 代付接口请求地址
            $resdata = go_curl($request_url, $json, 'post', 12);

            Log::record("平台订单号：{$parameters['order_id']}：游易付支付宝代付创建返回结果：{$resdata}", 'error');

            // 一般是第三方超时，结果为空
            if (empty($resdata)) {
                return ['code' => 200, 'other_order_id' => 102, 'msg' => '处理中', 'return_param' => $resdata];
            }

            // {"success":false,"msg":"请求数据格式错误，请检查后重新提交"
            // {"success":false,"state":2,"msg":"账户余额不足"}
            // {"success":true,"state":3,"msg":"受理成功稍后查询状态","transaction_id":"180731074401925049743836963013"}

            $resarray = json_decode($resdata, true);
            // 提示
            $msg = isset($resarray['msg']) ? $resarray['msg'] : '处理中';
            // 第三方订单号
            $other_order_id = isset($resarray['transaction_id']) ? $resarray['transaction_id'] : 100;
            // 状态
            $state = isset($resarray['state']) ? $resarray['state'] : 123456;

            // 失败：只要不是失败，都认为创建成功
            if ($state == 2) {
                return ['code' => 300, 'other_order_id' => $other_order_id, 'msg' => $msg, 'return_param' => $resdata];
            }

            // 第三方可能 502
            return ['code' => 200, 'other_order_id' => $other_order_id, 'msg' => $msg, 'return_param' => $resdata];
            /*
             * state
             * 如果是1表示转账已经完成，对方已经收到款，
             * 如果是2表示转账失败，金额退回到余额，
             * 如果是3表示银行已经挂起此交易
             */
        } catch (\Exception $e) {
            return ['code' => 200, 'other_order_id' => 1000, 'msg' => '处理中', 'return_param' => $e->getMessage()];
        }
    }

    /**
     * 游易付支付宝代付，验证订单号，是不是已经代付成功
     * @access public
     * @param  string   $order_id     本地订单号（第三方订单号）
     * @param  array    $pay_config   代付配置
     * @param  array    $other_param  其他参数
     * @param  boolean  $rule         返回规则
     * @param  boolean  $query_type   查询类型
     * @return array
     */
    public function youyifuPaidQuery($order_id = 0, $pay_config = [], $other_param = [], $rule = false, $query_type = false)
    {

        $arr['service'] = 'bankcardtransferquery';                         // 接口类型
        $arr['version'] = '1.0';                                           // 版本号
        $arr['charset'] = 'UTF-8';                                         // 字符集
        $arr['mch_id'] = $pay_config['merchant_id'];                       // 商户号，由平台分配
        $arr['transaction_id'] = $order_id;                                // 商户系统内部的订单号 ,32个字符内、 可包含字母,确保在商户系统唯一
        $arr['nonce_str'] = date('YmdHis') . rand(100000, 999999);         // 随机字符串，不长于 32 位

        ksort($arr);                                                       // 对数组进行排序
        $temp = '';
        foreach ($arr as $k => $v) {
            if ($v != null) {
                $temp = $temp . $k . '=' . $v . '&';                       // 遍历数组进行字符串的拼接
            }
        }
        $temp = substr($temp, 0, strlen($temp) - 1);

        $key = $pay_config['key'];
        $str = chunk_split($key, 64, "\n");
        $private_key = "-----BEGIN RSA PRIVATE KEY-----\n$str-----END RSA PRIVATE KEY-----\n";
        //$private_key = $pay_config['key'];                               // 私钥文件名获取私钥(内容)

        $pkey_get_private = openssl_pkey_get_private($private_key);        // 获取私钥
        $signature = '';
        openssl_sign($temp, $signature, $pkey_get_private, OPENSSL_ALGO_SHA1);    // 生成一个签名

        $arr['sign'] = base64_encode($signature);

        $json = json_encode($arr);
        $request_url = $pay_config['request_url_query'];                   // 代付接口请求地址
        $resdata = go_curl($request_url, $json, 'post', 12);

        Log::record("平台订单号：{$order_id}：游易付支付宝代付查询返回结果：{$resdata}", 'error');

        $resarray = json_decode($resdata, true);

        // 验证代付订单规则
        if ($rule) {
            if (isset($resarray['state'])) {
                switch ($resarray['state']) {
                    case '1':
                        return 2;  // 成功
                    case '2':
                        return 3;  // 失败
                    default:
                        return false;
                }
            }
            return false;
        }

        if (isset($resarray['success']) && $resarray['success'] == 'true') {
            return ['code' => 200, 'return_param' => substr($resdata, 0, 60000), 'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
        }
        return ['code' => 300, 'return_param' => substr($resdata, 0, 60000), 'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];

        /**
         * 
         * {"success":true,"msg":"发放成功","transaction_id":"1805311724379331573621223924","state":1}
         * {"success":false,"msg":"当前订单不存在"}
         * 
         * 1表示付款成功
         * 2表示付款失败
         * 3表示付款处理中
         */
    }

    /**
     * 游易付支付宝代付，查询帐号余额
     * @access public
     * @param  array   $pay_config  代付配置
     * @return array
     */
    public function youyifuPaidQueryCash($pay_config = [])
    {

        $arr['service'] = 'bankcardtransferbalance';                       // 接口类型
        $arr['version'] = '1.0';                                           // 版本号
        $arr['charset'] = 'UTF-8';                                         // 字符集
        $arr['mch_id'] = $pay_config['merchant_id'];                       // 商户号，由平台分配
        $arr['nonce_str'] = date('YmdHis') . rand(100000, 999999);         // 随机字符串，不长于 32 位

        ksort($arr);                                                       // 对数组进行排序
        $temp = '';
        foreach ($arr as $k => $v) {
            if ($v != null) {
                $temp = $temp . $k . '=' . $v . '&';                       // 遍历数组进行字符串的拼接
            }
        }
        $temp = substr($temp, 0, strlen($temp) - 1);

        $key = $pay_config['key'];
        $str = chunk_split($key, 64, "\n");
        $private_key = "-----BEGIN RSA PRIVATE KEY-----\n$str-----END RSA PRIVATE KEY-----\n";
        //$private_key = $pay_config['key'];                               // 私钥文件名获取私钥(内容)

        $pkey_get_private = openssl_pkey_get_private($private_key);        // 获取私钥
        $signature = '';
        openssl_sign($temp, $signature, $pkey_get_private, OPENSSL_ALGO_SHA1);    // 生成一个签名

        $arr['sign'] = base64_encode($signature);

        $json = json_encode($arr);
        $request_url = $pay_config['request_url_cash_query'];              // 代付接口请求地址
        $resdata = go_curl($request_url, $json, 'post', 12);

        Log::record("游易付支付宝代付查询帐号余额返回结果：{$resdata}", 'error');

        $resarray = json_decode($resdata, true);
        if (isset($resarray['success']) && $resarray['success'] == 'true') {
            return ['code' => 200, 'return_param' => substr($resdata, 0, 60000), 'cash' => $resarray['balance'], 'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
        }

        return ['code' => 300, 'return_param' => substr($resdata, 0, 60000), 'cash' => 0, 'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];

        /**
         * {"success":true,"msg":"查询成功","balance":"279993.99"}
         */
    }

    /**
     * 薪航向代付
     * @access public
     * @param  array  $parameters   创建订单参数
     * @param  array  $pay_config   代付配置
     * @return array
     */
    public function xhxPaid($parameters = [], $pay_config = [])
    {
        try {

            $merchantNo = $pay_config['merchant_id'];                             // 商户号，我司分配给客户的唯一编号

            // 上传银行用户信息 自由职业者签约
            if (1) {
                $data['name'] = $parameters['name'];                                                                      // 姓名
                $data['cardNo'] = $parameters['paid_class'] == 0 ? $parameters['bank_card'] : $parameters['account'];     // 卡号
                $data['idCardNo'] = $parameters['id_card'];                                                               // 身份证号码
                $data['Mobile'] = $parameters['mobile'];                                                                  // 手机号

                $aes_key = date('ymdHis') . rand(1000, 9999);

                $temp = chunk_split($pay_config['key'], 64, "\n");
                $key = "-----BEGIN RSA PRIVATE KEY-----\n$temp-----END RSA PRIVATE KEY-----\n";

                $temp = chunk_split($pay_config['other_public_key'], 64, "\n");
                $other_public_key = "-----BEGIN PUBLIC KEY-----\n$temp-----END PUBLIC KEY-----\n";

                $pu_key = openssl_pkey_get_public($other_public_key);
                openssl_public_encrypt($aes_key, $crypted, $pu_key, OPENSSL_PKCS1_PADDING);
                $encryptKey = base64_encode($crypted);

                $openssl_encrypt = openssl_encrypt(json_encode($data), 'AES-128-ECB', $aes_key,  1);
                $encryptData = base64_encode($openssl_encrypt);

                openssl_sign(json_encode($data), $signature, $key, OPENSSL_ALGO_SHA1);
                $sign = base64_encode($signature);

                $arr = [
                    'merchantNo'    => $merchantNo,
                    'encryptKey'    => $encryptKey,
                    'encryptData'   => $encryptData,
                    'sign'          => $sign
                ];
                $param = json_encode($arr);

                $header = array('Content-type:application/json;charset=UTF-8');
                $request_url = "https://taxpay.xiaozhucc.com/api/freelancer/v1/signUp";    // 接口请求地址
                $resdata = go_curl($request_url, $param, 'post', 12, $header);

                /*
                $resarray = json_decode($resdata, true);
                if (isset($resarray['data'])) {
                    $get_data = json_decode($resarray['data'], true);
                    $encryptKey = base64_decode($get_data['encryptKey']);
                    $pri_key = openssl_pkey_get_private($key);
                    openssl_private_decrypt($encryptKey, $encrypted, $pri_key, OPENSSL_PKCS1_PADDING);

                    $encryptData = base64_decode($get_data['encryptData']);
                    $resdata = openssl_decrypt($encryptData, 'AES-128-ECB', $encrypted, 1);
                    $info_arr = json_decode($resdata, true);

                    if (isset($info_arr['payResultList'][0]['resCode'])) {
                        $code = $info_arr['payResultList'][0]['resCode'];
                    }
                    if (isset($info_arr['payResultList'][0]['resMsg'])) {
                        $msg = $info_arr['payResultList'][0]['resMsg'];
                    }
                    if (isset($info_arr['payResultList'][0]['transOrderNum'])) {
                        $other_order_id = $info_arr['payResultList'][0]['transOrderNum'];
                    }
                }
                */
            }



            $data['totalCount'] = 1;                                              // 付款总笔数
            $data['totalAmt'] = $parameters['cash'];                              // 付款总金额
            $data['batchNo'] = $parameters['order_id'];                           // 商户批次号
            $data['channelNo'] = $parameters['paid_class'] == 0 ? 2000 : 1000;    // 通道编码，由我司人员提供 1000支付宝 2000银行卡

            $data['payItems'] =
                [
                    'orderNumber'   => $data['batchNo'], // 商户订单号
                    'payAmount'     => $data['totalAmt'], // 金额
                    'payeeName'     => $parameters['name'], // 收款人名称
                    'payeeAcc'      => $parameters['paid_class'] == 0 ? $parameters['bank_card'] : $parameters['account'], // 收款人账号  银行卡号/支付宝账号/微信号
                    'idCard'        => $parameters['id_card'], // 身份证号
                    'mobile'        => $parameters['mobile'], // 手机号
                    // 'bankBranchNo'      => '', // 联行号
                    // 'bankBranchName'    => '', // 支行名称
                    // 'province'          => '', // 省名称
                    // 'city'              => '', // 市名称 
                    'memo'          => '转账', // 备注
                    'payType'       => 0, // 代付类型 0：实时 1：工作日    （目前都是 0 实时结算）
                    'paymentType'   => $parameters['paid_class'] == 0 ? 0 : 1, // 代付方式 0：银行卡，1：支付宝，2：微信
                    'accType'       => 1, // 结算银行卡账号类型，0：对公1：对私（目前只支持对私）
                ];

            $aes_key = date('ymdHis') . rand(1000, 9999);

            $temp = chunk_split($pay_config['key'], 64, "\n");
            $key = "-----BEGIN RSA PRIVATE KEY-----\n$temp-----END RSA PRIVATE KEY-----\n";

            $temp = chunk_split($pay_config['other_public_key'], 64, "\n");
            $other_public_key = "-----BEGIN PUBLIC KEY-----\n$temp-----END PUBLIC KEY-----\n";

            $pu_key = openssl_pkey_get_public($other_public_key);
            openssl_public_encrypt($aes_key, $crypted, $pu_key, OPENSSL_PKCS1_PADDING);
            $encryptKey = base64_encode($crypted);

            $openssl_encrypt = openssl_encrypt(json_encode($data), 'AES-128-ECB', $aes_key,  1);
            $encryptData = base64_encode($openssl_encrypt);

            openssl_sign(json_encode($data), $signature, $key, OPENSSL_ALGO_SHA1);
            $sign = base64_encode($signature);

            $arr = [
                'merchantNo'    => $merchantNo,
                'encryptKey'    => $encryptKey,
                'encryptData'   => $encryptData,
                'sign'          => $sign
            ];
            $param = json_encode($arr);

            $header = array('Content-type:application/json;charset=UTF-8');
            $request_url = "https://taxpay.xiaozhucc.com/api/settle/v1/pay";    // 接口请求地址
            $resdata = go_curl($request_url, $param, 'post', 12, $header);

            Log::record("平台订单号：{$parameters['order_id']}：薪航向代付创建返回结果：{$resdata}", 'error');

            // 一般是第三方超时，结果为空
            if (empty($resdata)) {
                return ['code' => 200, 'other_order_id' => 102, 'msg' => '处理中', 'return_param' => $resdata];
            }

            $resarray = json_decode($resdata, true);

            $code = 1000;
            // 提示
            $msg = '处理中';
            // 第三方订单号
            $other_order_id = 100;

            if (isset($resarray['code'])) {
                $code = $resarray['code'];
            }

            if (isset($resarray['data'])) {
                $get_data = json_decode($resarray['data'], true);
                $encryptKey = base64_decode($get_data['encryptKey']);
                $pri_key = openssl_pkey_get_private($key);
                openssl_private_decrypt($encryptKey, $encrypted, $pri_key, OPENSSL_PKCS1_PADDING);

                $encryptData = base64_decode($get_data['encryptData']);
                $resdata = openssl_decrypt($encryptData, 'AES-128-ECB', $encrypted, 1);
                $info_arr = json_decode($resdata, true);

                if (isset($info_arr['payResultList'][0]['resCode'])) {
                    $code = $info_arr['payResultList'][0]['resCode'];
                }
                if (isset($info_arr['payResultList'][0]['resMsg'])) {
                    $msg = $info_arr['payResultList'][0]['resMsg'];
                }
                if (isset($info_arr['payResultList'][0]['transOrderNum'])) {
                    $other_order_id = $info_arr['payResultList'][0]['transOrderNum'];
                }
            }

            // 失败：只要不是失败，都认为创建成功
            if ($code > 1000) {
                return ['code' => 300, 'other_order_id' => $other_order_id, 'msg' => $msg, 'return_param' => $resdata];
            }

            // 第三方可能 502
            return ['code' => 200, 'other_order_id' => $other_order_id, 'msg' => $msg, 'return_param' => $resdata];
            /*
{
	"payResultList":[
		{
			"orderNumber":"23022216341554721016",
			"payAmount":1,
			"splitFlag":0,
			"resCode":"1003",
			"resMsg":"身份证号不正确"
		}
	],
	"batchNo":"23022216341554721016",
	"totalAmt":1,
	"successNum":0,
	"resCode":"0000",
	"resMsg":"success",
	"successAmount":0,
	"totalCount":1,
	"merchantNo":"MI364599222107766784"
}
{
	"payResultList":[
		{
			"orderNumber":"23022217170431472082",
			"payAmount":"1",
			"splitFlag":"0",
			"resCode":"0000",
			"transOrderNum":"2023022217170489001966080212",
			"resMsg":"请求付款成功"
		}
	],
	"batchNo":"23022217170431472082",
	"totalAmt":"1",
	"successNum":"1",
	"resCode":"0000",
	"resMsg":"success",
	"successAmount":"1",
	"totalCount":"1",
	"merchantNo":"MI364599222107766784"
}
            */
        } catch (\Exception $e) {
            return ['code' => 200, 'other_order_id' => 1000, 'msg' => '处理中', 'return_param' => $e->getMessage()];
        }
    }

    /**
     * 薪航向代付，验证订单号，是不是已经代付成功
     * @access public
     * @param  string   $order_id     本地订单号（第三方订单号）
     * @param  array    $pay_config   代付配置
     * @param  array    $other_param  其他参数
     * @param  boolean  $rule         返回规则
     * @param  boolean  $query_type   查询类型
     * @return array
     */
    public function xhxPaidQuery($order_id = 0, $pay_config = [], $other_param = [], $rule = false, $query_type = false)
    {

        $merchantNo = $pay_config['merchant_id'];    // 商户号，我司分配给客户的唯一编号
        $data['batchNo'] = $order_id;                // 商户批次号

        $data['queryItems'] =
            [
                'orderNumber'   => $data['batchNo'], // 商户订单号
            ];

        $aes_key = date('ymdHis') . rand(1000, 9999);

        $temp = chunk_split($pay_config['key'], 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n$temp-----END RSA PRIVATE KEY-----\n";

        $temp = chunk_split($pay_config['other_public_key'], 64, "\n");
        $other_public_key = "-----BEGIN PUBLIC KEY-----\n$temp-----END PUBLIC KEY-----\n";

        $pu_key = openssl_pkey_get_public($other_public_key);
        openssl_public_encrypt($aes_key, $crypted, $pu_key, OPENSSL_PKCS1_PADDING);
        $encryptKey = base64_encode($crypted);

        $openssl_encrypt = openssl_encrypt(json_encode($data), 'AES-128-ECB', $aes_key,  1);
        $encryptData = base64_encode($openssl_encrypt);

        openssl_sign(json_encode($data), $signature, $key, OPENSSL_ALGO_SHA1);
        $sign = base64_encode($signature);

        $arr = [
            'merchantNo'    => $merchantNo,
            'encryptKey'    => $encryptKey,
            'encryptData'   => $encryptData,
            'sign'          => $sign
        ];
        $param = json_encode($arr);

        $header = array('Content-type:application/json;charset=UTF-8');
        $request_url = "https://taxpay.xiaozhucc.com/api/settle/v1/payQuery";    // 接口请求地址
        $resdata = go_curl($request_url, $param, 'post', 12, $header);

        Log::record("平台订单号：{$order_id}：薪航向代付查询返回结果：{$resdata}", 'error');

        $resarray = json_decode($resdata, true);

        if (isset($resarray['code']) && $resarray['code'] > 1000) {
            $orderStatus = 3;
        }

        if (isset($resarray['data'])) {
            $get_data = json_decode($resarray['data'], true);
            $encryptKey = base64_decode($get_data['encryptKey']);
            $pri_key = openssl_pkey_get_private($key);
            openssl_private_decrypt($encryptKey, $encrypted, $pri_key, OPENSSL_PKCS1_PADDING);

            $encryptData = base64_decode($get_data['encryptData']);
            $resdata = openssl_decrypt($encryptData, 'AES-128-ECB', $encrypted, 1);
            $info_arr = json_decode($resdata, true);

            $orderStatus = $info_arr['queryItems'][0]['orderStatus'];
        }

        // 验证代付订单规则
        if ($rule) {
            if (isset($orderStatus)) {
                switch ($orderStatus) {
                    case '2':
                        return 2;  // 成功
                    case '3':
                        return 3;  // 失败
                    default:
                        return false;
                }
            }
            return false;
        }

        if (isset($orderStatus) && $orderStatus == '2') {
            return ['code' => 200, 'return_param' => substr($resdata, 0, 60000), 'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
        }
        return ['code' => 300, 'return_param' => substr($resdata, 0, 60000), 'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];

        /*
{
	"batchNo": "23022217170431472082",
	"queryItems": [{
		"orderNumber": "23022217170431472082",
		"payAmount": 1.00,
		"splitFlag": 0,
		"orderStatus": "2",
		"resCode": "0000",
		"transOrderNum": "2023022217170489001966080212",
		"resMsg": "结算成功"
	}],
	"merchantNo": "MI364599222107766784"
}
        */
    }

    /**
     * 薪航向代付，查询帐号余额
     * @access public
     * @param  array   $pay_config  代付配置
     * @return array
     */
    public function xhxPaidQueryCash($pay_config = [])
    {

        $merchantNo = $pay_config['merchant_id'];                             // 商户号，我司分配给客户的唯一编号
        $data['channelNo'] = $pay_config['paid_class'] == 0 ? 2000 : 1000;    // 通道编码，由我司人员提供 1000支付宝 2000银行卡

        $aes_key = date('ymdHis') . rand(1000, 9999);

        $temp = chunk_split($pay_config['key'], 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n$temp-----END RSA PRIVATE KEY-----\n";

        $temp = chunk_split($pay_config['other_public_key'], 64, "\n");
        $other_public_key = "-----BEGIN PUBLIC KEY-----\n$temp-----END PUBLIC KEY-----\n";

        $pu_key = openssl_pkey_get_public($other_public_key);
        openssl_public_encrypt($aes_key, $crypted, $pu_key, OPENSSL_PKCS1_PADDING);
        $encryptKey = base64_encode($crypted);

        $openssl_encrypt = openssl_encrypt(json_encode($data), 'AES-128-ECB', $aes_key,  1);
        $encryptData = base64_encode($openssl_encrypt);

        openssl_sign(json_encode($data), $signature, $key, OPENSSL_ALGO_SHA1);
        $sign = base64_encode($signature);

        $arr = [
            'merchantNo'    => $merchantNo,
            'encryptKey'    => $encryptKey,
            'encryptData'   => $encryptData,
            'sign'          => $sign
        ];
        $param = json_encode($arr);

        $header = array('Content-type:application/json;charset=UTF-8');
        $request_url = "https://taxpay.xiaozhucc.com/api/account/v1/payBalance";    // 接口请求地址
        $resdata = go_curl($request_url, $param, 'post', 12, $header);

        Log::record("薪航向代付查询帐号余额返回结果：{$resdata}", 'error');

        $resarray = json_decode($resdata, true);

        if (isset($resarray['data'])) {
            $get_data = json_decode($resarray['data'], true);
            $encryptKey = base64_decode($get_data['encryptKey']);
            $pri_key = openssl_pkey_get_private($key);
            openssl_private_decrypt($encryptKey, $encrypted, $pri_key, OPENSSL_PKCS1_PADDING);

            $encryptData = base64_decode($get_data['encryptData']);
            $resdata = openssl_decrypt($encryptData, 'AES-128-ECB', $encrypted, 1);
            $info_arr = json_decode($resdata, true);

            $balance = $info_arr['balance'];
        }

        if (isset($balance)) {
            return ['code' => 200, 'return_param' => substr($resdata, 0, 60000), 'cash' => $balance,  'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
        }

        return ['code' => 300, 'return_param' => substr($resdata, 0, 60000), 'cash' => 0, 'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];

        /*
{"balance":998.95,"frozenBalance":0.00,"canBalance":998.95,"merchantNo":"MI364599222107766784"}
        */
    }

    /**
     * 灵时云代付
     * @access public
     * @param  array  $parameters   创建订单参数
     * @param  array  $pay_config   代付配置
     * @return array
     */
    public function lsyPaid($parameters = [], $pay_config = [])
    {
        try {

            if (strlen($parameters['id_card']) == 18) {
                $age = date('Ymd') - substr($parameters['id_card'], 6, 8);
                if ($age < 160000 || $age > 600000) {
                    return ['code' => 400, 'other_order_id' => 0, 'msg' => '年龄不符合要求', 'return_param' => ''];
                }
            }

            // 上传银行用户信息 自由职业者签约
            if (1) {
                $data['memberCode'] = $pay_config['merchant_id'];    // 商户号
                $data['updateMarkNo'] = $parameters['order_id'];     // 上传标识编号，需要全局唯一，参与签名
                $data['timestamp'] = date('Y-m-d H:i:s');            // 时间戳，格式为：yyyy-MM-dd HH:mm:ss

                $data['workPeoples'] = [
                    [
                        'userName'       =>  $parameters['name'], // 姓名
                        'idCard'         =>  $parameters['id_card'], // 身份证号
                        'mobile'         =>  $parameters['mobile'], // 手机号
                        /*
                        'email'          => '', // 邮箱
                        'sex'            => '', // 性别 1 男、2 女
                        'address'        => '', // 地址
                        'idFrontPhoto'   => '', // 正面图片地址
                        'idBackPhoto'    => '', // 反面图片地址
                        'bankAccount'    => '', // 银行卡号
                        'alipayAccount'  => '', // 支付宝帐号
                        'contractUrl'    => '', // 合同链接
                        */
                    ],
                ]; // 待上传结算明细数据，不参与签名

                $key = $pay_config['key'];
                $string = 'keyappSecret' . $key . 'memberCode' . $data['memberCode'] . 'timestamp' . $data['timestamp'] . 'updateMarkNo' . $data['updateMarkNo'] . 'secret';
                $data['sign'] = strtoupper(sha1($string));
                $arr = json_encode($data);

                $header = array(
                    "Accept: application/json",
                    "Content-Type: application/json;charset=utf-8",
                );
                $request_url = "https://o.linsyun.com/api/WorkPeople/uploadMerlinWorkPeoples";    // 请求地址
                $resdata = go_curl($request_url, $arr, 'post', 12, $header);

                $resarray = json_decode($resdata, true);

                $code = 0;
                // 提示
                $msg = '处理中';
                // 第三方订单号
                $other_order_id = 100;

                if (isset($resarray['code'])) {
                    $code = $resarray['code'];
                }
                if (isset($resarray['data'][0]['remark'])) {
                    $msg = $resarray['data'][0]['remark'];
                }

                if ($code >= 1000) {
                    return ['code' => 300, 'other_order_id' => $other_order_id, 'msg' => $msg, 'return_param' => $resdata];
                }
            }

            $data['memberCode'] = $pay_config['merchant_id'];    // 商户号
            $data['updateMarkNo'] = $parameters['order_id'];     // 上传标识编号，需要全局唯一，参与签名
            $data['timestamp'] = date('Y-m-d H:i:s');            // 时间戳，格式为：yyyy-MM-dd HH:mm:ss
            $data['TaskNo'] = $pay_config['app_id'];             // 上传任务编号，不参与签名；（来源灵时云任务管理中任务编号）

            $data['workDetails'] = [
                [
                    'shopNo'         =>  $parameters['order_id'], // 商户流水号
                    'userName'       =>  $parameters['name'], // 姓名
                    'idCard'         =>  $parameters['id_card'], // 身份证号
                    'mobile'         =>  $parameters['mobile'], // 手机号
                    'grantType'      =>  $parameters['paid_class'] == 0 ? '银行' : '支付宝', // 下发类型包括：支付宝和银行；例如：银行
                    'accountName'    =>  $parameters['name'], // 账号名
                    'accountNumber'  =>  $parameters['paid_class'] == 0 ? $parameters['bank_card'] : $parameters['account'], // 账号（银行卡/支付宝）
                    'afterTaxAmount' =>  $parameters['cash'], // 税后金额（元）
                    'Remark'         =>  date('YmdHis'), // 备注
                ],
            ]; // 待上传结算明细数据，不参与签名

            $key = $pay_config['key'];
            $string = 'keyappSecret' . $key . 'memberCode' . $data['memberCode'] . 'timestamp' . $data['timestamp'] . 'updateMarkNo' . $data['updateMarkNo'] . 'secret';
            $data['sign'] = strtoupper(sha1($string));
            $arr = json_encode($data);

            $header = array(
                "Accept: application/json",
                "Content-Type: application/json;charset=utf-8",
            );
            $request_url = "https://o.linsyun.com/api/WorkPlan/UploadWorkPlan";    // 请求地址
            $resdata = go_curl($request_url, $arr, 'post', 12, $header);

            Log::record("平台订单号：{$parameters['order_id']}：灵时云代付创建返回结果：{$resdata}", 'error');

            // 一般是第三方超时，结果为空
            if (empty($resdata)) {
                return ['code' => 200, 'other_order_id' => 102, 'msg' => '处理中', 'return_param' => $resdata];
            }

            $resarray = json_decode($resdata, true);

            $code = 0;
            // 提示
            $msg = '处理中';
            // 第三方订单号
            $other_order_id = 100;

            if (isset($resarray['code'])) {
                $code = $resarray['code'];
            }
            if (isset($resarray['message'])) {
                $msg = $resarray['message'];
            }
            if (isset($resarray['data']['planNo'])) {
                $other_order_id = $resarray['data']['planNo'] ? $resarray['data']['planNo'] : 0;
            }

            // 失败：只要不是失败，都认为创建成功
            if ($code >= 1000) {
                return ['code' => 300, 'other_order_id' => $other_order_id, 'msg' => $msg, 'return_param' => $resdata];
            }

            // 第三方可能 502
            return ['code' => 200, 'other_order_id' => $other_order_id, 'msg' => $msg, 'return_param' => $resdata];
            /*
Array
(
    [data] => Array
        (
            [uploadMarkNo] => 
            [planNo] => 
            [failDetail] => Array
                (
                    [0] => Array
                        (
                            [shopNo] => 20230322094750
                            [currentGrantState] => 4
                            [failCause] => 账号非支付宝账号
                        )

                )

        )

    [code] => 1019
    [message] => 全订单明细未上传成功
    [messageType] => 1
)

Array
(
    [data] => Array
        (
            [uploadMarkNo] => 20230322095057
            [planNo] => ,TCAPIA29005,
            [failDetail] => Array
                (
                )

        )

    [code] => 0
    [message] => 成功
    [messageType] => 1
)
            */
        } catch (\Exception $e) {
            return ['code' => 200, 'other_order_id' => 1000, 'msg' => '处理中', 'return_param' => $e->getMessage()];
        }
    }

    /**
     * 灵时云代付，验证订单号，是不是已经代付成功
     * @access public
     * @param  string   $order_id     本地订单号（第三方订单号）
     * @param  array    $pay_config   代付配置
     * @param  array    $other_param  其他参数
     * @param  boolean  $rule         返回规则
     * @param  boolean  $query_type   查询类型
     * @return array
     */
    public function lsyPaidQuery($order_id = 0, $pay_config = [], $other_param = [], $rule = false, $query_type = false)
    {

        $data['memberCode'] = $pay_config['merchant_id'];    // 商户号
        $data['updateMarkNo'] = $order_id;                   // 上传标识编号，需要全局唯一，参与签名
        $data['timestamp'] = date('Y-m-d H:i:s');            // 时间戳，格式为：yyyy-MM-dd HH:mm:ss

        $key = $pay_config['key'];
        $string = 'keyappSecret' . $key . 'memberCode' . $data['memberCode'] . 'timestamp' . $data['timestamp'] . 'updateMarkNo' . $data['updateMarkNo'] . 'secret';
        $data['sign'] = strtoupper(sha1($string));
        $arr = json_encode($data);

        $header = array(
            "Accept: application/json",
            "Content-Type: application/json;charset=utf-8",
        );
        $request_url = "https://o.linsyun.com/api/WorkPlan/QueryWorkPlan";    // 请求地址
        $resdata = go_curl($request_url, $arr, 'post', 12, $header);

        Log::record("平台订单号：{$order_id}：灵时云代付查询返回结果：{$resdata}", 'error');

        $resarray = json_decode($resdata, true);

        if (isset($resarray['data'])) {
            if (isset($resarray['data']['planDetail'][0]['payState'])) {
                $payState = $resarray['data']['planDetail'][0]['payState'];
            }
        }

        // 验证代付订单规则
        if ($rule) {
            if (isset($payState)) {
                switch ($payState) {
                    case '3':
                        return 2;  // 成功
                    case '4':
                        return 3;  // 失败
                    default:
                        return false;
                }
            }
            return false;
        }

        if (isset($payState) && $payState == '3') {
            return ['code' => 200, 'return_param' => substr($resdata, 0, 60000), 'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
        }
        return ['code' => 300, 'return_param' => substr($resdata, 0, 60000), 'data' => json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];

        /*
Array
(
    [data] => Array
        (
            [planNo] => TCAPIA29005
            [planAuditState] => 2
            [planName] => TCAPIA29005
            [completeFbState] => 1
            [planDetail] => Array
                (
                    [0] => Array
                        (
                            [userName] => 贺正华
                            [idCard] => 429004199206081436
                            [afterTaxAmount] => 1
                            [payState] => 1
                            [payFinishTime] => 0001-01-01 00:00:00
                            [failReason] => 
                            [customerOrderNo] => 801230322093798879381
                            [shopNo] => 20230322095057
                            [externalNo] => 
                            [remark] => 20230322095057
                        )

                )

        )

    [code] => 0
    [message] => 成功
    [messageType] => 1
)

payState
1 待打款 2 打款中 3 打款成功 4 打款失败
        */
    }

    /**
     * 灵时云代付，查询帐号余额
     * @access public
     * @param  array   $pay_config  代付配置
     * @return array
     */
    public function lsyPaidQueryCash($pay_config = [])
    {
        return ['code' => 300, 'return_param' => '灵时云代付无查询余额接口', 'cash' => 0, 'data' => '灵时云代付无查询余额接口'];
    }

    /**
     * 手动代付
     * @access public
     * @param  array  $parameters   创建订单参数
     * @param  array  $pay_config   代付配置
     * @return array
     */
    public function shoudongPaid($parameters = [], $pay_config = [])
    {
        try {

            $this->dayStatistics($parameters, $pay_config, 1);

            return ['code' => 200, 'other_order_id' => $parameters['order_id'], 'msg' => '处理中', 'return_param' => ''];
        } catch (\Exception $e) {
            return ['code' => 200, 'other_order_id' => 1000, 'msg' => '处理中', 'return_param' => $e->getMessage()];
        }
    }

    /**
     * 手动代付，验证订单号，是不是已经代付成功
     * @access public
     * @param  string   $order_id     本地订单号（第三方订单号）
     * @param  array    $pay_config   代付配置
     * @param  array    $other_param  其他参数
     * @param  boolean  $rule         返回规则
     * @param  boolean  $query_type   查询类型
     * @return array
     */
    public function shoudongPaidQuery($order_id = 0, $pay_config = [], $other_param = [], $rule = false, $query_type = false)
    {
        return ['code' => 300, 'return_param' => '', 'data' => ''];
    }

    /**
     * 手动代付，查询帐号余额
     * @access public
     * @param  array   $pay_config  代付配置
     * @return array
     */
    public function shoudongPaidQueryCash($pay_config = [])
    {
        return ['code' => 300, 'return_param' => '手动代付无查询余额接口', 'cash' => 0, 'data' => '手动代付无查询余额接口'];
    }

    /**
     * 天统计
     * @access public
     * @param  array  $parameters   创建订单参数
     * @param  array  $pay_config   代付配置
     * @param  string $mode         方式 
     * @return mixed
     */
    public function dayStatistics($parameters = [], $pay_config = [], $mode = 1)
    {
        if ($mode == 1) {
            $paid_cash = $parameters['cash'] * 100;
            $expire = strtotime(date('Y-m-d', strtotime('+1 day'))) - time();

            // 更新商户号今天已经代付的金额总数
            $merchant_day_alipay_paid_cash_sum = $parameters['merchant_id'] . '_day_alipay_paid_cash_sum';
            $now_merchant_day_alipay_paid_cash_sum = $this->redis->has($merchant_day_alipay_paid_cash_sum);
            if ($now_merchant_day_alipay_paid_cash_sum) {
                $this->redis->inc($merchant_day_alipay_paid_cash_sum, $paid_cash);
            } else {
                $this->redis->set($merchant_day_alipay_paid_cash_sum, $paid_cash, $expire);
            }

            // 更新代付公司中的子商户号今天已经代付的金额总数
            $children_day_paid_cash_sum = $pay_config['name'] . '_day_paid_cash_sum';
            $now_children_day_paid_cash_sum = $this->redis->has($children_day_paid_cash_sum);
            if ($now_children_day_paid_cash_sum) {
                $this->redis->inc($children_day_paid_cash_sum, $paid_cash);
            } else {
                $this->redis->set($children_day_paid_cash_sum, $paid_cash, $expire);
            }

            // 通道每天最多代付成功次数
            $children_company_success_count = $pay_config['name'] . '_success_count';
            $now_children_company_success_count = $this->redis->has($children_company_success_count);
            if ($now_children_company_success_count) {
                $this->redis->inc($children_company_success_count, 1);
            } else {
                $this->redis->set($children_company_success_count, 1, $expire);
            }

            // 通道每天最多代付用户成功次数（支付宝）
            if ($pay_config['user_success_count'] != '0') {
                $children_company_user_success_count = $pay_config['name'] . '_user_' . $parameters['account'];
                $now_children_company_user_success_count = $this->redis->has($children_company_user_success_count);
                if ($now_children_company_user_success_count) {
                    $this->redis->inc($children_company_user_success_count, 1);
                } else {
                    $this->redis->set($children_company_user_success_count, 1, $expire);
                }
            }
        }

        if ($mode == 0) {
            $paid_cash = $parameters['cash'] * 100;
            $expire = strtotime(date('Y-m-d', strtotime('+1 day'))) - time();

            // 更新商户号今天已经代付的金额总数
            $merchant_day_alipay_paid_cash_sum = $parameters['merchant_id'] . '_day_alipay_paid_cash_sum';
            $now_merchant_day_alipay_paid_cash_sum = $this->redis->has($merchant_day_alipay_paid_cash_sum);
            if ($now_merchant_day_alipay_paid_cash_sum) {
                $this->redis->dec($merchant_day_alipay_paid_cash_sum, $paid_cash);
            } else {
                $this->redis->set($merchant_day_alipay_paid_cash_sum, $paid_cash, $expire);
            }

            // 更新代付公司中的子商户号今天已经代付的金额总数
            $children_day_paid_cash_sum = $pay_config['name'] . '_day_paid_cash_sum';
            $now_children_day_paid_cash_sum = $this->redis->has($children_day_paid_cash_sum);
            if ($now_children_day_paid_cash_sum) {
                $this->redis->dec($children_day_paid_cash_sum, $paid_cash);
            } else {
                $this->redis->set($children_day_paid_cash_sum, $paid_cash, $expire);
            }

            // 通道每天最多代付成功次数
            $children_company_success_count = $pay_config['name'] . '_success_count';
            $now_children_company_success_count = $this->redis->has($children_company_success_count);
            if ($now_children_company_success_count) {
                $this->redis->dec($children_company_success_count, 1);
            } else {
                $this->redis->set($children_company_success_count, 1, $expire);
            }

            // 通道每天最多代付用户成功次数（支付宝）
            if ($pay_config['user_success_count'] != '0') {
                $children_company_user_success_count = $pay_config['name'] . '_user_' . $parameters['account'];
                $now_children_company_user_success_count = $this->redis->has($children_company_user_success_count);
                if ($now_children_company_user_success_count) {
                    $this->redis->dec($children_company_user_success_count, 1);
                } else {
                    $this->redis->set($children_company_user_success_count, 1, $expire);
                }
            }
        }
    }
}
